//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    //个人中心页面三个实时记录
    attendlottery: 0,
    makelottery: 0,
    luckylottery: 0
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function() {
    //授权登录部分
    if (app.globalData.userInfo) {
      // console.log("重新切换到个人中心时:" + app.globalData.userInfo);
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        // console.log("进入小程序时：" + app.globalData.userInfo);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          console.log("test:" + app.globalData.userInfo)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    //获取用户参与抽奖次数、发起抽奖次数、中奖记录次数
    var that = this
    var user = wx.getStorageSync('user') || [];
    if (app.globalData.userInfo) {
      console.log(app.globalData.userInfo)
      wx.request({
        url: app.globalData.ip + '/jeesite/lottery/wechatUser/getUserInformation',
        data: {
          openid: user.openid,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: 'POST',
        success: function(result) {
          //对参与抽奖数，发起抽奖数，中奖记录数进行初始化
          console.log(result.data)
          that.setData({
            attendlottery: result.data.attendlottery,
            makelottery: result.data.makelottery,
            luckylottery: result.data.luckylottery
          })
        },
        fail: function(result) {
          wx.showModal({
            title: '页面初始化失败！',
            content: '服务器崩了吧~',
            showCancel: false,
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onLoad(); //实时监听数据显示
  },

  //用户点击进行授权
  getUserInfo: function(e) {
    //参与抽奖+发起抽奖+中奖记录
    console.log("centeropenid:" + app.globalData.openid);

    var that = this
    if (e.detail.userInfo) {
      var objz = {};
      objz = e.detail.userInfo;
      wx.setStorageSync('userInfo', objz); //存储userInfo
      app.globalData.userInfo = e.detail.userInfo
    }
    //从本地缓存获取Openid和userInfo
    var user = wx.getStorageSync('user') || [];
    var userInfo = wx.getStorageSync('userInfo') || [];

    //将openid和userInfo的值传给后台 
    if (e.detail.userInfo) {
      wx.login({
        success: function(res) {
          wx.request({
            url: app.globalData.ip + '/jeesite/lottery/wechatUser/login',
            data: {
              openid: user.openid,
              image: userInfo.avatarUrl,
              nickname: userInfo.nickName,
              country: userInfo.country,
              province: userInfo.province,
              city: userInfo.city
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: function(result) {
              that.setData({
                userInfo: e.detail.userInfo,
                hasUserInfo: true
              })
              console.log(result.data)
              //对参与抽奖数，发起抽奖数，中奖记录数进行初始化
              that.setData({ //想要同时更新前台页面，必须用setData函数！！！
                attendlottery: result.data.attendlottery,
                makelottery: result.data.makelottery,
                luckylottery: result.data.luckylottery
              })
              wx.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 1000
              });
            },
            fail: function(result) {
              wx.showModal({
                title: '授权失败！',
                content: '服务器崩了吧~',
                showCancel: false,
              })
            }
          })
        }
      })
    }
  },

  //查看地址列表
  checkAddressList: function() {
    var flag = 1; //flag=1代表是从个人中心去到的地址列表（-1代表是从中奖记录进入的地址列表）
    wx.navigateTo({
      url: '../addressList/addressList?flag=' + flag
    });
  },

  //参与抽奖页面
  attend: function () {
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: '../attendlottery/attendlottery'
      });
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }
  },

  //发起抽奖页面
  make: function () {
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: '../makelottery/makelottery'
      });
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }

  },

  //中奖记录页面
  luckylogs: function () {
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: '../luckytime/luckytime'
      });
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }
  }
})